package cn.conac.rc.share.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.jpa.Restrictions;
import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.framework.utils.DateUtils;
import cn.conac.rc.share.entity.ShareAreaEntity;
import cn.conac.rc.share.repository.ShareAreaRepository;
import cn.conac.rc.share.vo.SharedAreaVo;

/**
 * ShareAreaService类
 *
 * @author serviceCreator
 * @date 2017-07-21
 * @version 1.0
 */
@Service
public class ShareAreaService extends GenericService<ShareAreaEntity, Integer> {

	@Autowired
	private ShareAreaRepository repository;

	/**
	 * 动态查询，分页，排序查询
	 * @param vo
	 * @return Page
	 * @throws Exception
	 */
	public List<SharedAreaVo> findSharedAreaList(String areaCode) throws Exception {
		try {
			
			long remDays  = -1;
			SharedAreaVo sharedAreaVo = null;
			List<SharedAreaVo> sharedAreaVoList = new ArrayList<SharedAreaVo>();
			Sort sort = new Sort(Direction.DESC, "endTime");
			Criteria<ShareAreaEntity> dc = this.createCriteria(areaCode);
			List<ShareAreaEntity> shareAreaEntityList =  repository.findAll(dc, sort);
			for(ShareAreaEntity shareAreaEntity : shareAreaEntityList) {
				remDays = DateUtils.remDays(shareAreaEntity.getEndTime());
				if(remDays >= 0) {
					sharedAreaVo = new SharedAreaVo();
					sharedAreaVo.setId(shareAreaEntity.getId());
					sharedAreaVo.setShareInfoId(shareAreaEntity.getShareInfoId());
					if(areaCode.equals(shareAreaEntity.getAreaCodeDest())) {
						sharedAreaVo.setAreaCode(shareAreaEntity.getAreaCodeSource());
						sharedAreaVo.setAreaName(shareAreaEntity.getAreaNameSourceRe());
					} else {
						sharedAreaVo.setAreaCode(shareAreaEntity.getAreaCodeDest());
						sharedAreaVo.setAreaName(shareAreaEntity.getAreaNameDestRe());
					}
					sharedAreaVo.setEndTime(shareAreaEntity.getEndTime());
					sharedAreaVo.setRemDays(remDays);
					sharedAreaVoList.add(sharedAreaVo);
				}
			}
			return sharedAreaVoList;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 动态查询条件
	 * @param areaCode
	 * @return Criteria
	 */
	private Criteria<ShareAreaEntity> createCriteria(String areaCode) {
		Criteria<ShareAreaEntity> dc = new Criteria<ShareAreaEntity>();
		dc.add(Restrictions.or(Restrictions.eq("areaCodeSource", areaCode, true),
				Restrictions.eq("areaCodeDest", areaCode, true)));
		return dc;
	}

}
